<template>
  <div class="document-edit">
    <div class="edit-container">
      <div style="display: flex; flex-direction: column; gap: 0.5rem;">
        <div style="display: flex; gap: 0.5rem; padding: 0.5rem;">
          <div style="display: flex; align-items: center; flex: 3;">
            <span>标题：</span>

            <el-input
                v-model="editingDocument.name"
                style="flex: 3;"
                placeholder="请输入标题"
                clearable/>
          </div>

          <div style="display: flex; align-items: center; flex: 1;">
            <span>权限：</span>

            <el-select
                v-model="editingDocument.permission"
                placeholder="请选择权限" style="flex: 1;">
              <el-option
                  v-for="item in permissionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
            </el-select>
          </div>

          <el-button type="primary" :loading="saving" @click="onSave">保存</el-button>
        </div>
      </div>

      <div class="edit-form">
        <!-- 文档内容 -->
        <div class="form-group content-group">
          <textarea
              ref="contentTextarea"
              v-model="editingDocument.content"
              class="form-textarea content-textarea"
              rows="20"
              @keydown="handleTextareaKeydown"
              @paste="handlePaste"/>
        </div>

        <!-- 实时预览区域 (右侧50%) -->
        <div class="preview-panel">
          <div class="preview-content">
            <div class="preview-markdown">
              <MarkdownRenderer
                  :content="editingDocument.content || '暂无内容'"
                  :theme="selectedTheme"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, computed, watch} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'
import type {Doc} from '@/modules/doc/types/doc.ts'
import type {NameSpace} from '@/modules/doc/types/namespace.ts'
import type {MarkdownTheme} from '@/components/MarkdownRenderer.vue'
import {useDocDetail, useDoc} from '@/modules/doc/composables'
import {namespaceApi} from '@/modules/doc/api'
import {toast} from '@/utils/message.ts'
import {index as fileApi} from '@/modules/file/api'
import {ElMessage} from 'element-plus'

const route = useRoute()
const router = useRouter()

// 使用 composables
const {fetchDocumentDetail} = useDocDetail()
const {updateDocument, createDocument} = useDoc()

const document = ref<Doc | null>(null)
const saving = ref(false)
const selectedTheme = ref<MarkdownTheme>('classic')
const contentTextarea = ref<HTMLTextAreaElement | null>(null)

// 命名空间和权限相关状态
const namespaces = ref<NameSpace[]>([])
const editingDocument = reactive({
  name: '',
  content: '',
  namespaceId: '',
  permission: 0  // 默认私有
})

// 判断是否为新建模式
const isCreateMode = computed(() => route.path === '/doc/create')

// 权限选项
const permissionOptions = [
  {label: '私有', value: 0},
  {label: '公开', value: 1}
]

// 加载命名空间列表
const loadNamespaces = async () => {
  try {
    namespaces.value = await namespaceApi.getAll()
  } catch (error) {
    console.error('加载命名空间列表失败:', error)
    toast.error('加载命名空间列表失败')
  }
}

// 加载文档数据
const loadDocument = async () => {
  if (isCreateMode.value) {
    // 新建模式：不加载文档，设置空白状态
    document.value = null
    editingDocument.name = ''
    editingDocument.content = ''

    // 从query参数获取命名空间ID（如果有）
    const spaceId = route.query.spaceId as string
    editingDocument.namespaceId = spaceId || (namespaces.value[0]?.id || '')
    editingDocument.permission = 0  // 默认私有

    // 设置页面标题
    window.document.title = '新建文档 - 懒熊文档'

    // 恢复用户的主题选择
    const savedTheme = localStorage.getItem('markdown-edit-theme')
    if (savedTheme) {
      selectedTheme.value = savedTheme as MarkdownTheme
    }
    return
  }

  const docId = route.params.id as string
  if (!docId) {
    toast.error('缺少文档ID')
    router.push('/doc')
    return
  }

  try {
    const doc = await fetchDocumentDetail(docId, {
      showLoading: true,
      showError: true
    })

    if (doc) {
      document.value = doc

      // 设置页面标题
      window.document.title = `编辑文档: ${doc.name} - 懒熊文档`

      // 初始化编辑表单数据
      editingDocument.name = doc.name
      editingDocument.content = doc.content || ''
      editingDocument.namespaceId = doc.namespaceId || ''
      editingDocument.permission = doc.permission ?? 0
    }

    // 恢复用户的主题选择
    const savedTheme = localStorage.getItem('markdown-edit-theme')
    if (savedTheme) {
      selectedTheme.value = savedTheme as MarkdownTheme
    }
  } catch (error) {
    console.error('加载文档失败:', error)
    toast.error('文档加载失败')
    router.push('/doc')
  }
}

// 监听主题变化，保存到本地
watch(selectedTheme, (newTheme) => {
  localStorage.setItem('markdown-edit-theme', newTheme)
})

// 保存文档
const onSave = async () => {
  if (!editingDocument.name.trim()) {
    toast.warning('请输入文档标题')
    return
  }

  saving.value = true
  try {
    if (isCreateMode.value) {
      // 新建文档
      const spaceId = route.query.spaceId as string
      if (!spaceId) {
        toast.error('缺少空间ID')
        return
      }

      const newDoc = {
        name: editingDocument.name.trim(),
        content: editingDocument.content,
        namespaceId: spaceId,
        permission: editingDocument.permission
      }

      const documentId = await createDocument(newDoc)

      // 创建成功，跳转到新创建的文档详情页
      router.push(`/doc/${documentId}`)
    } else {
      // 编辑现有文档
      if (!document.value) return

      // 构建更新数据，明确包含parentId（即使为null也要传递）
      const updatedDoc: any = {
        name: editingDocument.name.trim(),
        content: editingDocument.content,
        permission: editingDocument.permission,
        namespaceId: document.value.namespaceId,
        sortNo: document.value.sortNo,
        layoutType: document.value.layoutType,
        isShowToc: document.value.isShowToc
      }

      // 显式添加parentId，包括null值
      if (document.value.parentId !== undefined) {
        updatedDoc.parentId = document.value.parentId
      } else {
        updatedDoc.parentId = null
      }

      await updateDocument(document.value.id, updatedDoc)

      // 返回详情页面
      router.push(`/doc/${document.value.id}`)
    }
  } catch (error) {
    console.error('保存文档失败:', error)
    toast.error('保存文档失败')
  } finally {
    saving.value = false
  }
}

// 取消编辑
const onCancel = () => {
  if (isCreateMode.value) {
    // 新建模式：返回文档首页
    router.push('/doc')
  } else if (document.value) {
    // 编辑模式：返回文档详情页
    router.push(`/doc/${document.value.id}`)
  } else {
    router.push('/doc')
  }
}

// 处理粘贴事件，自动上传图片
const handlePaste = async (event: ClipboardEvent) => {
  const items = event.clipboardData?.items
  if (!items) return

  // 查找图片项
  for (let i = 0; i < items.length; i++) {
    const item = items[i]

    // 检查是否为图片
    if (item.type.indexOf('image') !== -1) {
      event.preventDefault() // 阻止默认粘贴行为

      const file = item.getAsFile()
      if (!file) continue

      try {
        // 显示上传中提示
        const loadingMessage = ElMessage({
          message: '正在上传图片...',
          type: 'info',
          duration: 0
        })

        // 上传图片到OSS，指定doc目录
        const result = await fileApi.uploadFile(file, 'doc')

        // 关闭上传提示
        loadingMessage.close()

        if (result && result.fileUrl) {
          // 获取当前光标位置
          const textarea = contentTextarea.value
          if (!textarea) return

          const start = textarea.selectionStart
          const end = textarea.selectionEnd
          const content = editingDocument.content

          // 生成Markdown图片语法
          const imageMarkdown = `![${result.fileName || 'image'}](${result.fileUrl})`

          // 在光标位置插入图片URL
          const newContent = content.substring(0, start) + imageMarkdown + content.substring(end)
          editingDocument.content = newContent

          // 恢复光标位置（在插入的图片Markdown后面）
          setTimeout(() => {
            const newPosition = start + imageMarkdown.length
            textarea.selectionStart = textarea.selectionEnd = newPosition
            textarea.focus()
          }, 0)

          ElMessage.success('图片上传成功')
        } else {
          ElMessage.error('图片上传失败：无效的响应')
        }
      } catch (error) {
        console.error('上传图片失败:', error)
        ElMessage.error('图片上传失败')
      }

      break // 只处理第一张图片
    }
  }
}

// 处理textarea的Tab键缩进
const handleTextareaKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Tab') {
    event.preventDefault()

    const textarea = contentTextarea.value
    if (!textarea) return

    const start = textarea.selectionStart
    const end = textarea.selectionEnd
    const content = editingDocument.content

    // 插入Tab字符（使用两个空格）
    const tabChar = '  '
    const newContent = content.substring(0, start) + tabChar + content.substring(end)

    editingDocument.content = newContent

    // 恢复光标位置（在插入的Tab后面）
    setTimeout(() => {
      textarea.selectionStart = textarea.selectionEnd = start + tabChar.length
    }, 0)
  }
}

// 键盘快捷键支持
const handleKeydown = (event: KeyboardEvent) => {
  // Ctrl+S / Cmd+S 保存
  if ((event.ctrlKey || event.metaKey) && event.key === 's') {
    event.preventDefault()
    onSave()
  }
  // Esc 取消
  if (event.key === 'Escape') {
    onCancel()
  }
}

onMounted(async () => {
  // 先加载命名空间列表
  await loadNamespaces()

  // 再加载文档数据（需要命名空间数据）
  await loadDocument()

  // 添加键盘事件监听
  window.addEventListener('keydown', handleKeydown)
})

// 组件卸载时移除事件监听
import {onUnmounted} from 'vue'

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.document-edit {
  min-height: calc(100vh - 80px);
  background: #f8f9fa;
}

.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 80px);
}

.spinner {
  font-size: 1.2rem;
  color: #666;
}

.edit-container {
  height: calc(100vh - 80px);
  display: flex;
  flex-direction: column;
  background: white;
}

/* 编辑表单区域 */
.edit-form {
  flex: 1;
  border-right: 1px solid #e1e1e1;
  display: flex;
  background: white;
  gap: 0.5rem;
}

.form-header {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e1e1e1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8f9fa;
  flex-shrink: 0;
}

.form-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.2rem;
  font-weight: 600;
}

.form-actions {
  display: flex;
  gap: 0.5rem;
}

.form-content {
  flex: 1;
  padding: 1.5rem;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #2c3e50;
  font-weight: 500;
  font-size: 0.9rem;
}

.form-input,
.form-select {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #e1e1e1;
  border-radius: 6px;
  font-size: 0.9rem;
  transition: border-color 0.2s;
  background: white;
}

.form-input:focus,
.form-select:focus {
  outline: none;
  border-color: #42b883;
  box-shadow: 0 0 0 2px rgba(66, 184, 131, 0.1);
}

.title-input {
  font-weight: 600;
  font-size: 1.1rem;
}

.content-group {
  flex: 1;
  width: 50%;
  display: flex;
  flex-direction: column;
  margin-bottom: 0;
}

.form-textarea {
  width: 100%;
  flex: 1;
  min-height: 300px;
  padding: 0.75rem;
  border: 1px solid #e1e1e1;
  border-radius: 6px;
  font-size: 0.9rem;
  font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
  line-height: 1.5;
  resize: none;
  transition: border-color 0.2s;
  background: white;
}

.form-textarea:focus {
  outline: none;
  border-color: #42b883;
  box-shadow: 0 0 0 2px rgba(66, 184, 131, 0.1);
}

/* 预览区域 */
.preview-panel {
  width: 50%;
  display: flex;
  flex-direction: column;
  background: white;
}

.preview-header {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e1e1e1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8f9fa;
  flex-shrink: 0;
}

.preview-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.2rem;
  font-weight: 600;
}

.preview-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.word-count {
  font-size: 0.8rem;
  color: #666;
  background: #e9ecef;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
}

.preview-content {
  flex: 1;
  overflow-y: auto;
  background: white;
}

.preview-title {
  font-size: 1.8rem;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 1.5rem;
  padding-bottom: 0.5rem;
  border-bottom: 2px solid #42b883;
}

.preview-markdown {
  line-height: 1.6;
}

/* 移除MarkdownRenderer内部第一个元素的上边距，确保与左侧对齐 */
.preview-markdown :deep(> div > *:first-child) {
  margin-top: 0 !important;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .edit-container {
    flex-direction: column;
  }

  .edit-form {
    width: 100%;
    height: 50%;
    border-right: none;
    border-bottom: 1px solid #e1e1e1;
  }

  .preview-panel {
    width: 100%;
    height: 50%;
  }

  .form-textarea {
    min-height: 200px;
  }
}

@media (max-width: 768px) {
  .form-header {
    padding: 0.75rem 1rem;
  }

  .form-header h3 {
    font-size: 1.1rem;
  }

  .preview-header {
    padding: 0.75rem 1rem;
  }

  .preview-header h3 {
    font-size: 1.1rem;
  }

  .form-content,
  .preview-content {
    padding: 1rem;
  }

  .preview-title {
    font-size: 1.5rem;
  }
}

/* 深色模式适配 */
.dark .document-edit {
  background: #1a1a1a;
}

.dark .edit-container {
  background: #1a1a1a;
}

.dark .edit-form,
.dark .preview-panel {
  background: #1a1a1a;
  border-color: #3d3d3d;
}

.dark .form-header,
.dark .preview-header {
  background: #2d2d2d;
  border-bottom-color: #3d3d3d;
}

.dark .form-header h3,
.dark .preview-header h3 {
  color: #e6e6e6;
}

.dark .edit-form {
  border-right-color: #3d3d3d;
}

.dark .form-group label {
  color: #e6e6e6;
}

.dark .form-input,
.dark .form-select,
.dark .form-textarea {
  background: #2d2d2d;
  border-color: #3d3d3d;
  color: #e6e6e6;
}

.dark .form-input:focus,
.dark .form-select:focus,
.dark .form-textarea:focus {
  border-color: #42b883;
  box-shadow: 0 0 0 2px rgba(66, 184, 131, 0.2);
}

.dark .word-count {
  background: #3d3d3d;
  color: #b3b3b3;
}

.dark .preview-title {
  color: #e6e6e6;
}

.dark .preview-content {
  background: #1a1a1a;
}

.dark .preview-markdown {
  color: #e6e6e6;
}

@media (max-width: 1200px) {
  .dark .edit-form {
    border-right: none;
    border-bottom-color: #3d3d3d;
  }
}

/* 滚动条样式 */
.form-content::-webkit-scrollbar,
.preview-content::-webkit-scrollbar {
  width: 6px;
}

.form-content::-webkit-scrollbar-track,
.preview-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.form-content::-webkit-scrollbar-thumb,
.preview-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.form-content::-webkit-scrollbar-thumb:hover,
.preview-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.dark .form-content::-webkit-scrollbar-track,
.dark .preview-content::-webkit-scrollbar-track {
  background: #2d2d2d;
}

.dark .form-content::-webkit-scrollbar-thumb,
.dark .preview-content::-webkit-scrollbar-thumb {
  background: #555;
}

.dark .form-content::-webkit-scrollbar-thumb:hover,
.dark .preview-content::-webkit-scrollbar-thumb:hover {
  background: #666;
}
</style>